package com.johnson.news.fragment;


import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.johnson.news.BR;
import com.johnson.news.R;
import com.johnson.news.activity.NewsDetailActivity;
import com.johnson.news.databinding.FragmentSearchBinding;
import com.johnson.news.model.bean.NewsItem;
import com.johnson.news.model.bean.SearchResult;
import com.johnson.news.model.remote.RemoteDataSource;
import com.johnson.news.util.Utils;
import com.youmbe.library.BaseBindingFragment;
import com.youmbe.library.BaseRecyclerAdapter;
import com.youmbe.library.util.MyToast;

import java.util.ArrayList;

import static com.johnson.news.util.Utils.PAGE_SIZE;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SearchFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SearchFragment extends BaseBindingFragment<FragmentSearchBinding> {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public SearchFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SearchFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SearchFragment newInstance(String param1, String param2) {
        SearchFragment fragment = new SearchFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    InputMethodManager inputMethodManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

    }

    View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
        }

        return rootView;
    }

    BaseRecyclerAdapter<NewsItem> adapter;

    @Override
    public void init() {
        adapter = new BaseRecyclerAdapter<>(getActivity(), R.layout.adapter_news, com.johnson.news.BR.data);
        dataBinding.searchResultList.setAdapter(adapter);
        dataBinding.searchResultList.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter.setBindingViewClickListener(BR.onClickListener, onClickListener);

        dataBinding.searchBut.setOnClickListener(onClickListener);
        dataBinding.searchClean.setOnClickListener(onClickListener);

        dataBinding.searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    dataBinding.searchClean.setVisibility(View.GONE);
                } else
                    dataBinding.searchClean.setVisibility(View.VISIBLE);
            }
        });

        dataBinding.searchResultList.setLoadingMoreEnabled(true);
        dataBinding.searchResultList.setPullRefreshEnabled(false);
        dataBinding.searchResultList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                page++;
                getData();
            }
        });
    }

    int page = 0;

    String keyWords;
    void getData() {
        if (TextUtils.isEmpty(keyWords)) {
            MyToast.showToast("请输入关键字", getActivity());
            return;
        }
        RemoteDataSource.getRemoteDataSource()
                .search(getActivity(), Utils.MID, keyWords, PAGE_SIZE, page)
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        dataBinding.searchResultList.refreshComplete();
                        dataBinding.searchResultList.loadMoreComplete();
                    }
                })
                .subscribe(new Consumer<ArrayList<NewsItem>>() {
                    @Override
                    public void accept(ArrayList<NewsItem> searchResult) throws Exception {
                        if (page <= 1) {
                            if (searchResult.size() == 0) {
                                dataBinding.searchNoResult.setVisibility(View.VISIBLE);
                            } else
                                dataBinding.searchNoResult.setVisibility(View.GONE);
                            adapter.setData(searchResult);
                        } else {
                            dataBinding.searchNoResult.setVisibility(View.GONE);
                            adapter.addData(searchResult);
                        }
                    }
                });
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.news_layout) {
                Object object = v.getTag(R.id.adapter_tag_data);
                if (object != null && object instanceof NewsItem) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("data", (NewsItem) object);
                    startActivity(NewsDetailActivity.class, bundle);
                }
            } else if (v.getId() == R.id.search_but) {
                page = 1;
                keyWords = dataBinding.searchEdit.getText().toString();
                inputMethodManager.hideSoftInputFromWindow(dataBinding.searchEdit.getWindowToken(), 0);
                getData();
            } else if(v.getId() == R.id.search_clean) {
                dataBinding.searchEdit.setText("");
            }
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.fragment_search;
    }

}
